// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import axios from 'axios';
const service = axios.create({
    // baseURL: process.env.NODE_ENV === 'production' ? 'https://live-test.mtygs.cn/api/' : 'https://live-test.mtygs.cn/api/',
    baseURL: process.env.NODE_ENV === 'production' ? 'https://live.mtygs.cn/api/' : 'https://live.mtygs.cn/api/',
    timeout: 60000, // 过期时间
});

// request interceptor
service.interceptors.request.use(
    (config) => {
        if (/get/i.test(config.method)) {
            config.params = config.params || {};
            config.params.temp = Date.parse(new Date()) / 1000;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
);

// response interceptor
service.interceptors.response.use(
    (response) => {
        const res = response.data;
        const { errorCode, result, errorMessages, success } = res;
        if (!success) {
            if (errorCode === '0000111') {
                localStorage.removeItem('token')
                return false
            }
            alert(typeof (errorMessages) === 'string' ? errorMessages : JSON.stringify(errorMessages))
            return false
        }
        return result;
    },
    (error) => {
        alert(error.message)
        return false
    },
);
export function generateUniqueString() {
    return (Date.now().toString(36) + Math.random().toString(36).substr(2, 10)).substr(0, 10);
}

export async function apiPost(url, data = {}) {
    const token = window.localStorage.getItem('token')
    let dataJosn = {
        parameter: data,
        appId: '',
        circleId: '',
        requestId: generateUniqueString(),
        traceId: generateUniqueString(),
        token: token ? token : '',
    }
    return service({
        url,
        method: 'post',
        data: dataJosn,
    });
}

export default service;
